/* Filename: mycpy.c
 * Description: 3.系统调用IO-read,writer,lseek及mycopy的实现
 * Last modified: humble 20200119 10:04
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define BUFLEN (1024)

void usage(void) { printf("Usage:...\n"); }

int main(int argc, char **argv) {
    if(argc != 3){ fprintf(stderr, "argc != 2\n"); usage(); exit(1); }

    int sfd = open(argv[1], O_RDONLY);
    if(sfd < 0){ fprintf(stderr, "sfd\n"); usage(); exit(1); }

    int dfd = open(argv[2], O_WRONLY|O_TRUNC|O_CREAT, 0600);
    if(dfd < 0){ fprintf(stderr, "dfd\n"); usage(); close(sfd); /*记得关闭*/ exit(1); }

    char buf[BUFLEN] = {0};
    ssize_t rdlen = 0,
            wrlen = 0;
    int wrcnt = 3,
        pos = 0;
    while(1){
        rdlen = read(sfd, buf, BUFLEN);
        if(rdlen < 0){ fprintf(stderr, "rdlen < 0\n"); break; }
        if(rdlen == 0){ break; } // 读完了

        pos = 0;
        wrcnt = 3; // 尝试写3次
        while(rdlen > 0){
            if(--wrcnt < 0){ fprintf(stderr, "write failed\n"); exit(1); }

            wrlen = write(dfd, buf + pos, rdlen);
            if(wrlen < 0){ fprintf(stderr, "wrlen < 0\n"); exit(1); }

            pos += wrlen;
            rdlen -= wrlen;
        }
    }

    close(sfd);
    close(dfd);
    return 0;
}
